import client, { UserRoleVo } from '@lib/client'
import { Button, Form, message, Modal, Select } from 'antd'
import React, { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import ReactMarkdown from 'react-markdown'

export interface IAssignRoleButtonProps {
  refresh: () => void
  userId?: string
}

export default function AssignRoleButton(props: IAssignRoleButtonProps) {
  const { t } = useTranslation()
  const { refresh, userId } = props
  const [form] = Form.useForm()
  const [visible, setVisible] = useState(false)
  const [isPosting, setIsPosting] = useState(false)
  const [roleList, setRoleList] = useState([] as UserRoleVo[])

  const handleOpen = async (userId) => {
    await Promise.all([
      client.getInstance().getRoleList(),
      client.getInstance().getUserRole(userId),
    ]).then((res) => {
      const { data: dataRoleList } = res[0]
      setRoleList(dataRoleList?.roles ?? [])

      const { data: dataUserRole } = res[1]
      const userRoleIds =
        dataUserRole?.user_role?.map((item) => item.role_id + '') ?? []

      form.setFieldsValue({
        roles: userRoleIds,
        userId: userId,
      })
      setVisible(true)
    })
  }

  const handleClose = useCallback(() => {
    setVisible(false)
    setIsPosting(false)
  }, [])

  const handleFinish = useCallback(async (values) => {
    try {
      setIsPosting(true)
      const r = await client.getInstance().saveUserRole({
        user_id: values.userId,
        role_id: values.roles.map((role) => parseInt(role)),
      })
      if (r.status == 200) {
        message.success('Success')
        setVisible(false)
        refresh()
      }
    } finally {
      setIsPosting(false)
    }
  }, [])

  return (
    <>
      <a onClick={() => handleOpen(userId)}>
        {t('user_list.button.assign_role')}
      </a>
      <Modal
        title={t('user_list.modal.assign_role.title')}
        visible={visible}
        destroyOnClose
        onCancel={handleClose}
        width={600}
        footer={null}
      >
        <ReactMarkdown source={t('user_list.modal.assign_role.desc')} />
        <Form onFinish={handleFinish} form={form}>
          <Form.Item name="roles" wrapperCol={{ span: 24 }}>
            <Select mode="multiple">
              {roleList.map((role) => (
                <Select.Option key={role.id} value={role.id + ''}>
                  {role.description}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item hidden name="userId"></Form.Item>
          <Form.Item wrapperCol={{ span: 24, offset: 21 }}>
            <Button type="primary" htmlType="submit" loading={isPosting}>
              {t('user_list.modal.assign_role.submit')}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
